<template>
    <view class="container">
        <view class="relation-list">
            <p class="tip">请完善至少 <em class="tip_em">2</em> 条紧急联系人</p>
            <template v-for="(item, index) in relationList" :key="index">
                <view class="relation-card" v-if="item.status != '0'">
                    <view class="form-item">
                        <text class="label">姓名</text>
                        <input class="input" type="text" v-model="item.name" placeholder="请输入姓名" />
                    </view>
                    <view class="form-item">
                        <text class="label">手机号</text>
                        <!-- #ifdef H5 -->
                        <input class="input" type="text" v-model="item.mobile" placeholder="请输入手机号" />
                        <!-- #endif -->

                        <!-- #ifndef H5 -->
                        <input class="input" type="text" v-model="item.mobile" placeholder="请输入手机号" :disabled="!!item.id" />
                        <!-- #endif -->
                    </view>
                    <view class="form-item">
                        <text class="label">关系</text>
                        <div class="flex-1">
                            <picker @change="handleRelationChange($event, index)" :value="getRelationIndex(item.relationType)" :range="relationOptions" range-key="label">
                                <view class="picker">
                                    {{item.relationType ? getRelationLabel(item.relationType) : '请选择关系'}}
                                </view>
                            </picker>
                        </div>
                    </view>
                    <view class="form-item">
                        <text class="label">备注</text>
                        <input class="input" type="text" v-model="item.remark" placeholder="备注（选填）" />
                    </view>
                    <view class="card-actions">
                        <text class="delete" v-if="!item.id" @tap="handleDelete(item, index)">删除</text>
                        <text class="save" @tap="handleSave(index)">添加</text>
                    </view>
                </view>
            </template>
        </view>
        <view class="empty_add" v-if="actRelationLength == 0" @tap="handleSave(0)">添加</view>
        <button v-if="actRelationLength != 0" class="submit-btn" @click="relactionSubmit">保存</button>
    </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import Interact from '@/utils/interact';
import { editUserRelation, getUserRelations } from '@/api/user';
import { onLoad } from '@dcloudio/uni-app';
import { useStore } from 'vuex';
import permision from "@/utils/permission";
const Store = useStore();

let navBackCount = 1
let pageFrom = ''
onLoad((options: any) => {
    if(options.navBackCount) {
        navBackCount = +options.navBackCount
    }
    pageFrom = options.from || ''
    getUserRelations({}).then(res => {
        relationList.value = res.data || [];
    })
})

const relationOptions = [
    // { value: '00', label: '本人' },
    { value: '01', label: '父亲' },
    { value: '02', label: '母亲' },
    { value: '09', label: '夫妻' },
    { value: '10', label: '朋友' },
    { value: '03', label: '奶奶' },
    { value: '04', label: '爷爷' },
    { value: '05', label: '外公' },
    { value: '06', label: '外婆' },
    { value: '07', label: '亲戚' },
    { value: '08', label: '其他' }
];

type RelationInfo = {
    id?: string;
    name: string;
    mobile: string;
    relationType: string;
    remark: string;
    status?: string;
}
// 初始化一个空的联系人作为添加表单
const relationList = ref<RelationInfo[]>([{
    id: '',
    name: '',
    mobile: '',
    relationType: '',
    remark: '',
}]);

const actRelationLength = computed(() => {
    return relationList.value.filter(item => item.status != '0').length;
});

// 处理保存/添加
const handleSave = async (index: number) => {

    // #ifdef APP-PLUS

    const toConcat = () => {
         uni.navigateTo({
            url: '/pages/user/contact',
            events: {
                contactInfo: (data: any) => {
                    relationList.value.push({
                        id: '',
                        name: data.name,
                        mobile: data.mobile && data.mobile.replace(/\s+|-/ig, ''),
                        relationType: '',
                        remark: '',
                    });
                    console.log(data);
                }
            },
            fail(err) {
                console.log(err);
            },
        })
    }

    if(plus.os.name == "iOS") {
        let iosRes = permision.judgeIosPermission("contact")
        console.log(iosRes);
        if(iosRes == 0) {
            toConcat()
        } else if(iosRes == 3) {
            toConcat()
        } else {
            Interact.modal({
                title: '权限请求失败',
                message: '您已拒绝获取通讯录，请在设置中授予通讯录权限。',
                showCancel: true
            }).then(action => {
                if(action.confirm) {
                    permision.gotoAppPermissionSetting()
                }
            })
        }

    } else if(plus.os.name == 'Android') {
        let androidRes = await permision.requestAndroidPermission( "android.permission.READ_CONTACTS" );
        console.log(androidRes);
        if (androidRes == 1) {
            console.log("已获得授权");
            toConcat()
        } else {
            Interact.modal({
                title: '权限请求失败',
                message: '应用需要读取通讯录权限才能为您提供更好的服务，请在设置中授予该权限。'
            })
        }
    }
    // #endif

    // #ifdef MP-ALIPAY
    my.choosePhoneContact({
        success: (res: any) => {
            // choosePhoneContact  mobile name
            console.log("choosePhoneContact", res)
            relationList.value.push({
                id: '',
                name: res.name,
                mobile: res.mobile && res.mobile.replace(/\s+/ig, ''),
                relationType: '',
                remark: '',
            });
        },
        fail: (err: any) => {
            if(err.error == 2002) {
                my.openSetting({
                    contact: true
                })
            } else {
                Interact.toast(err.errorMessage)
            }
        },
    });
    // #endif

    // #ifdef H5
    relationList.value.push({
        id: '',
        name: '',
        mobile: '',
        relationType: '',
        remark: '',
    });
    // #endif

};
const handleDelete = async (item: RelationInfo, index: number) => {
    if(item.id) {
        let action = await Interact.modal({
            title: '提示',
            message: '确定要删除该联系人吗？',
            showCancel: true,
        })
        if(action.cancel) return;
        item.status = '0';
    } else {
        relationList.value.splice(index, 1);
    }
};


// 获取关系选项的索引
const getRelationIndex = (relationType: string) => {
    return relationOptions.findIndex(item => item.value === relationType);
};
const getRelationLabel = (relationType: string) => {
    let item = relationOptions.find(item => item.value === relationType);
    if(item) {
        return item.label;
    } else {
        return '';
    }
};

// 处理关系选择
const handleRelationChange = (e: any, index: number) => {
    const optionIndex = e.detail.value;
    relationList.value[index].relationType = relationOptions[optionIndex].value;
};



// 验证联系人信息
const validateContact = (contact: RelationInfo) => {
    if (!contact.name) return '请输入联系人姓名';
    if (!contact.mobile) return '请输入联系人手机号';
    if (!contact.relationType) return '请选择与联系人关系';
    if (!/^1\d{10}$/.test(contact.mobile)) return '请输入正确的手机号码';
    return '';
};


const relactionSubmit = () => {
    console.log(relationList.value);
    // 验证联系人信息
    const errors = relationList.value.map(contact => validateContact(contact));
    let errorItem = errors.find(error => error);
    if (errorItem) {
        Interact.toast(errorItem);
        return;
    }

    if(actRelationLength.value < 2) return Interact.toast('请添加至少2条不同的联系人');
    let mobileSet = new Set()
    let enableRealtionList = relationList.value.filter(item => item.status != '0')
    enableRealtionList.forEach((item: any) => {
        mobileSet.add(item.mobile)
    })
    let mobileArr =  Array.from(mobileSet)
    if(mobileArr.length < 2) return Interact.toast('请添加至少2条不同的联系人');

    editUserRelation({
        data: JSON.stringify(relationList.value),
    }).then(res => {
        Interact.modal('添加成功').then(() => {
            if(pageFrom == 'order') {
                Store.state.control.createOrderPromiseResolve('relactionship')
                Store.commit("control/SET_CREATE_ORDER_PROMISE_RESOLVE", null);
            } else {
                uni.navigateBack({
                    delta: navBackCount
                });
            }
        })
    })
}
</script>

<style lang="scss">
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
    padding: 30rpx;
}

.tip{
    padding: 10rpx 0;
    display: flex;
    margin-bottom: 20rpx;
    .tip_em{
        color: red;
        font-weight: bold;
        margin: 0 5rpx;
    }
}
.relation-list {
    .relation-card {
        background: #fff;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

        &.add-card {
            border: 2rpx dashed #ddd;
            box-shadow: none;
        }

        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 16rpx;

            .name {
                font-size: 32rpx;
                font-weight: bold;
                margin-right: 16rpx;
            }

            .relation {
                font-size: 24rpx;
                color: #dda62f;
                background: rgba(221,166,47,0.1);
                padding: 4rpx 12rpx;
                border-radius: 4rpx;
            }
        }

        .card-content {
            .phone {
                font-size: 28rpx;
                color: #666;
                margin-bottom: 8rpx;
            }

            .remark {
                font-size: 26rpx;
                color: #999;
            }
        }

        .card-actions {
            margin-top: 16rpx;
            text-align: right;
            display: flex;
            justify-content: flex-end;
            gap: 20rpx;

            .delete {
                color: #ff4d4f;
                font-size: 26rpx;
            }

            .save {
                color: #dda62f;
                font-size: 26rpx;
            }
        }
    }
}

.form-item {
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    .label {
        width: 120rpx;
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        flex-shrink: 0;
    }

    .input {
        flex: 1;
        height: 80rpx;
        border: 1rpx solid #eee;
        border-radius: 8rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
    }

    .picker {
        width: 100%;
        height: 80rpx;
        border: 1rpx solid #eee;
        border-radius: 8rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
        display: flex;
        align-items: center;
    }
}

.submit-btn {
    width: 100%;
    height: 88rpx;
    background: #dda62f;
    color: #fff;
    border-radius: 44rpx;
    font-size: 32rpx;
}

.empty_add{
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #12ab1e;
    color: #fff;
    border-radius: 44rpx;
    font-size: 32rpx;
    margin-bottom: 20rpx;
    margin-left: auto;
}
</style>
